import React from 'react';
import './index.less';

class Td extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      inputValue: this.props.value,
    };
  }
  showEditInput=(value) => {
    if (value === 'yes') {
      this.setState({ show: true });
    } else if (value === 'no') {
      this.setState({ show: false });
    }
  }
  handleOnChange=(value, key) => {
    const { inputValue } = this.state;
    inputValue[key] = value;
    this.setState({ inputValue: { ...this.state.inputValue } });
  }
  sureEdit=() => {
    const { inputValue } = this.state;
    this.setState({ show: false });
    this.props.sureEdit(inputValue);
  }
  render() {
    const { index, value = {} } = this.props;
    const { show, inputValue } = this.state;
    const cls = !show ? '' : 'hide';
    const hide = show ? '' : 'hide';

    return (
      <React.Fragment>
        <td>{index + 1}</td>
        <td className={cls}>{inputValue.name}</td>
        <td className={hide}>
          <input
            className="module-input"
            type="text"
            value={inputValue.name || ''}
            onChange={e => this.handleOnChange(e.target.value, 'name')}
          />
        </td>
        <td>
          <button className={`sure-button ${cls}`} onClick={() => this.showEditInput('yes')}>编辑</button>
          <button className={`green-button ${hide}`} onClick={this.sureEdit}>保存</button>
          <button className={`clearButton ${hide}`} onClick={() => this.showEditInput('no')}>取消</button>
        </td>
      </React.Fragment>
    );
  }
}
// Td.defaultProps = {
//   value: {
//     name: '',
//     descr: '',
//   }
// };

export default Td;
